<!--
父子关联下拉框
mc-parent-config:{api:{url:'数据地址' method:'post'|'get' params:[] fields:[],limit:10}  pkField:'id' pkTextField:'name'}
mc-child-config:{api:{url:'数据地址' method:'post'|'get' params:[] fields:[],limit:10}  pkField:'id' pkTextField:'name','parentField':'父亲字段'}
:p-model.sync : 父亲绑定的字段名 也可以不填写
v-model:儿子绑定的字段名
-->

<template>
  <el-row class="mc-parent-child-select">
    <el-col :span="12">
      <el-select v-model="parentValue" @focus="focus" :loading="loading" v-bind="$attrs" filterable remote :remote-method="parentSearch" :placeholder="mcParentComment"  @change="parentChange" @visible-change="parentClick">
        <template #prefix><i :class="mcPrefixIcon || 'el-icon-search'"></i></template>
        <el-option v-for="(item,idx) in parentOptions" :key="item.k" :label="item.v" :value="item.k" ></el-option>
      </el-select>
    </el-col>
    <el-col :span="12">
      <el-select @focus="focus" v-model="childValue" :loading="loading"  v-bind="$attrs" v-on="$listeners" filterable remote :remote-method="childSearch" :placeholder="mcChildComment" @change="childChange"   @visible-change="childClick" v-if="parentValue">
        <slot/>
        <el-option v-for="(item,idx) in childOptions" :key="item.k" :label="item.v" :value="item.k"></el-option>
      </el-select>
    </el-col>
  </el-row>
</template>

<script>
export default {
  name: 'mc-parent-child-select',
  data () {
    return {
      parentOptions:[],
      childOptions:[],
      loading:false,
      //优化下
      triggerWatch:true
    }
  },

  props:[
  'mcParentConfig','mcChildConfig','value','pModel','mcParentComment','mcChildComment',
    'mcvp1','mcvp2','mcvp3','mcvp4','mcvp5','mcvp6','mcvp7','mcvp8','mcvp9','mcvp10',
    'mcvc1','mcvc2','mcvc3','mcvc4','mcvc5','mcvc6','mcvc7','mcvc8','mcvc9','mcvc10',
    'mcPrefixIcon'
  ],
  computed:{
      childValue:{
        get:function (){
          return this.value;
        },
        set:function (v){
          this.$emit("input",v);
        }
      },
      parentValue:{
        get:function (){
          return this.pModel;
        },
        set:function (v){
          this.$emit("update:p-model",v);
        }
      }
    },
    watch:{
        parentValue(){
          if(this.triggerWatch){
            this.parentSearch(null,this.parentValue);
          }
        },
        childValue(){
          if(this.triggerWatch){
            this.childSearch(null,null,this.childValue);
          }
        }
    },
  mounted () {
      if(this.childValue || this.childValue===0){
        this.childSearch(null,null,this.childValue);
      }else if(this.parentValue || this.parentValue===0){
        this.parentSearch(null,this.parentValue);
      }
  },
  methods:{
    focus(e){
      if(window.iframeUi) {
        try {window.iframeUi.fastKey._triggerClickElem(e);}catch(e1) {}
      }
      this.$emit("focus",e)
    },
        buildAxiosParam(config,mcKeyword,parentValue,selfValue,suffix){
            var request = this.$magicaltool.request;
            var url = config.api.url;
            var method = config.api.method||'post';
            var limit = config.api.limit||20;
            var param = {};
            var ncv = request.util.collectMcNameCompareValue(this,suffix);
            if(request.util.isMcQueryUrl(url) || request.util.isContentTypeJson(config.api.contentType)){
                param = request.util.paramsTomMcQuery(ncv||config.api.params);
                if(config.api.fields && config.api.fields.length>0){
                    param.fields = config.api.fields
                }
                url += url.indexOf("?")!=-1 ? "&" : "?";
                url += "limit="+limit;
                //智能搜索 like
                if(mcKeyword){
                    param.param[config.pkTextField] = mcKeyword;
                    param.condition[config.pkTextField] = "like";
                }else{
                    //如果刚开始有值 v-model 就要定点查询了
                    if(selfValue!=null){
                        param.param[config.pkField] = selfValue;//加个自己外键查询
                    }
                }
                if(config.parentField && parentValue!=null){
                    param.param[config.parentField] = parentValue;//加个父亲ID
                }
                param.order = request.util.mcQueryOrder(config.api.orders);
            }else{
                param = request.util.paramsToJson(ncv||config.api.params);
                param.mcKeyword=mcKeyword;//加个关键词入参
                if(selfValue!=null){
                    param[config.pkField] = selfValue;//加个外键查询
                }
                if(config.parentField && parentValue!=null){
                    param[config.parentField] = parentValue;//加个外键查询
                }
                param.limit = limit;//加个关键词入参
            }
            return {cache:true,contentType:config.api.contentType,$vue:this,url:url,method:method,param:param}
        },
        buildResults(config,res){
          var list = res.data;
          var results = [];
           if(list){
              for(var n=0;n<list.length;n++){
                  var item = list[n];
                  results.push({k:item[config.pkField],v:item[config.pkTextField],p:item[config.parentField]});
              }
           }
          return results;
        },
       childSearch(mcKeyword,parentValue,selfValue){
          if(mcKeyword!==null){
            parentValue = this.parentValue;
          }
          var request = this.$magicaltool.request;
          var _t = this;
          var config = this.mcChildConfig;
          if(config){
              var url = config.api.url;
              if(url){
                  this.loading = true;
                  request.axios(this.buildAxiosParam(config,mcKeyword,parentValue,selfValue,'c')).then( res => {
                      _t.loading = false;
                      var results = _t.buildResults(config,res);
                      _t.childOptions = results;
                      //把父亲渲染出来吧
                      if(parentValue==null){
                        for(var i=0;i<results.length;i++){
                          if(results[i].k === selfValue ){
                            parentValue = results[i].p;
                            this.parentValue = parentValue;
                            break;
                          }
                        }
                        //找父亲下拉框
                        _t.parentSearch(null,parentValue)
                      }

                  })

              }
          }
      },
      parentSearch(mcKeyword,parentValue){
          var request = this.$magicaltool.request;
          var _t = this;
          var config = this.mcParentConfig;
          if(config){
              var url = config.api.url;
              if(url){
                  this.loading = true;
                  request.axios(this.buildAxiosParam(config,mcKeyword,null,parentValue,'p')).then(res => {
                      _t.loading = false;
                      var results = _t.buildResults(config,res);
                      _t.parentOptions = results;
                  })

              }
          }
      },
      notTriggerWatch(){
        this.triggerWatch = false;
        this.$nextTick(() => {
          this.triggerWatch = true;
        });
      },
      parentChange(parentValue){
          this.notTriggerWatch();
          this.childValue=null;
          this.childSearch(null,parentValue,null)
      },

      childChange(){
        this.notTriggerWatch();
      },
      parentClick(visible){
        if(visible){//显示
          this.parentSearch(null,null);
        }
      },
      childClick(visible){
        if(visible){
          this.childSearch(null,this.parentValue,null)
        }
      },

  }
}
</script>

<style lang="scss">
.mc-parent-child-select{
  .el-select{
    width:100%;
  }
}
  .mc-parent-child-select{
    .el-input__prefix{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      i{
        margin-left: 4px;
      }
    }
  }
</style>
